﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;

namespace Lucky_bgy
{
    public partial class Form1 : Form
    {
        //TODO 奖项修改后，增加重新载入的方法。
        public Form1()
        {
            InitializeComponent();
            SetStyle(ControlStyles.UserPaint, true);
            SetStyle(ControlStyles.AllPaintingInWmPaint, true); // 禁止擦除背景.
            SetStyle(ControlStyles.DoubleBuffer, true); // 双缓冲
        }

        AutoSizeFormClass asc = new AutoSizeFormClass();

        int btnState = 1;  //按钮状态 1 开始 2 停止 3 下一个奖项
        int currentPrize = 0; //当前在抽的奖项
        int sumLabel = 0;//滚动区总数量
        int dtCanPrizeIndex = 0; //当前索引
        int allowPrizeCount = 24;//单次允许的最多抽奖人数
        int screenWidth = 0;//屏幕宽
        int screenHeight = 0;//屏幕高
        static public int addCurrentPrizeCount = 0;//补抽人数
        
        DataTable dtCanPrize = new DataTable(); //参与抽奖的人员
        DataTable dtWinner = new DataTable();
        
        DBHelper helper = new DBHelper();

        private void Form1_Load(object sender, EventArgs e)
        {
            //窗口自适应初始化
            asc.controllInitializeSize(this);

            //界面初始化
            frontInit();

            //奖项初始化
            loadPrizeList();

            //参与人员初始化
            loadCanPrize();

        }

        private void frontInit()
        {
            //取屏幕高宽
            Rectangle rect = new Rectangle();
            rect = Screen.GetWorkingArea(this);
            screenWidth =rect.Width;//屏幕宽
            screenHeight = rect.Height;//屏幕高

            //滚动区背景初始化
            panel1.BackColor = Color.FromArgb(35, Color.White);
            panel_winner.BackColor = Color.FromArgb(50, Color.White);

            //文字性初始化
            main_title.Text = ConfigHelper.get("main_title").ToString();
            sub_title.Text = ConfigHelper.get("sub_title").ToString();
            setStateBar(ConfigHelper.get("default_welcome")); //默认欢迎的话

            //背景图片初始化
            btn_begin.BackgroundImage = imageList1.Images[0];
            btn_begin.Update();

            label_winner.ForeColor = Color.Gold;
            label_winner.Font = new Font("隶书", 18, FontStyle.Bold);

            timer_winner.Start();
        }

        /// <summary>
        /// 载入能参与抽奖的人
        /// </summary>
        public void loadCanPrize()
        {
            string str = "";
            if (ConfigHelper.get("repeat_flag").Equals("1")) //允许重复中奖
            {
                str = "select * from bs_user";
            }
            else
            {
                str = "select * from bs_user as a where not exists(select 1 from bs_winner as b where b.valid_flag = 1 and b.tel =  a.tel)";
            }
            
            dtCanPrize = helper.ExecuteDataTable(str, null);
        }

        /// <summary>
        /// 载入奖项
        /// </summary>
        public void loadPrizeList()
        {
            
            DataTable dt = helper.ExecuteDataTable("select ID,prize_name from bs_prize order by seq_order",null);
            cbox_prize_list.DataSource = dt;
            cbox_prize_list.DisplayMember = "prize_name";
            cbox_prize_list.ValueMember = "ID";
        }

        /// <summary>
        /// 重载音乐
        /// </summary>
        /// <param name="musicName"></param>
        private void reloadMusic(string musicName)
        {
            player_bg.currentPlaylist.clear();//清除播放的内容
            player_bg.URL = System.Environment.CurrentDirectory + "\\resources\\" + musicName;
            player_bg.Ctlcontrols.play();

        }

        /// <summary>
        /// 退出菜单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void logout_Click(object sender, EventArgs e)
        {
            helper.CloseConnection();
            System.Environment.Exit(0);
        }

        /// <summary>
        /// 设置菜单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void setting_Click(object sender, EventArgs e)
        {
            setting childrenForm = new setting();
            childrenForm.Show();

            //loadCanPrize();
            //loadPrizeList();
        }

        private void Form1_SizeChanged(object sender, EventArgs e)
        {
            asc.controlAutoSize(this);
        }

        /// <summary>
        /// 播放音乐菜单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void begin_Click(object sender, EventArgs e)
        {
            reloadMusic("music_bg.mp3");
        }

        /// <summary>
        /// 补抽按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void addOne_Click(object sender, EventArgs e)
        {
            //contextMenuStrip1.Items["addOne"].Enabled = false;
            allowMenuBtn(false);

            currentPrize = int.Parse(cbox_prize_list.SelectedValue.ToString());
            addCurrentPrize form = new addCurrentPrize();
            form.ShowDialog();
            if (addCurrentPrizeCount > 0 && addCurrentPrizeCount < 21)
            {
                addCurrentPrize();
            }
            else
            {
                MessageBox.Show("请输入1到20的数字");
            }
            
        }

        /// <summary>
        /// 清空中奖名单，清空已中奖人数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void reset_Click(object sender, EventArgs e)
        {
            DialogResult dr = MessageBox.Show("确认重新开始抽奖？这将清空所有已中奖名单，并不可恢复", "", MessageBoxButtons.YesNo);
            if (dr == DialogResult.Yes)
            {
                helper.ExecuteNonQuery("delete * from bs_winner", null);
                helper.ExecuteNonQuery("update bs_prize set use_total=0", null);
                loadCanPrize();
                resetWinnerLabel();
            }
        }

        /// <summary>
        /// 重抽当前奖项
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void resetCurrent_Click(object sender, EventArgs e)
        {
            DialogResult dr = MessageBox.Show("确认清空【" + cbox_prize_list.Text + "】的中奖名单？一旦确认，操作不可撤销", "", MessageBoxButtons.YesNo);
            if (dr == DialogResult.Yes)
            {
                helper.ExecuteNonQuery("delete * from bs_winner where prize_id="+currentPrize, null);
                helper.ExecuteNonQuery("update bs_prize set use_total=0 where id="+currentPrize, null);
                loadCanPrize();
                resetWinnerLabel();
            }
        }

        /// <summary>
        /// 抽奖按钮点击
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_begin_Click(object sender, EventArgs e)
        {
            

            //开始 ， 屏幕滚动 ，音乐响起，状态栏状态改变
            if (btnState == 1)
            {
                currentPrize = int.Parse(cbox_prize_list.SelectedValue.ToString());

                int dtCanPrizeCount = dtCanPrize.Rows.Count; //能抽奖的人员总数

                if (dtCanPrizeCount == 0)
                {
                    MessageBox.Show("全部嘉宾都已经中奖，或请先导入参与抽奖的用户");
                    return;
                }

                
                if (startPrize() == 0)//设置按钮状态，只有成功开始，才需要设置按钮上的字
                {
                    setBtnText(2);
                    
                    
                }
            }
            else if (btnState == 2) //停止 ， 获奖区添加获奖名单，写bs_winner表 ，更新prize表的use_total 
            {
                setStateBar("恭喜以上嘉宾，期待您下一次中奖");
                stopPrize();
                setBtnText(1);
            }

            

        }

        /// <summary>
        /// 设置状态栏
        /// </summary>
        /// <param name="str"></param>
        private void setStateBar(string str)
        {
            label_process.Text = str;
        }

        /// <summary>
        /// 补抽
        /// </summary>
        private void addCurrentPrize()
        {
            //MessageBox.Show(addCurrentPrizeCount.ToString());



            if (addCurrentPrizeCount > dtCanPrize.Rows.Count)
            {
                MessageBox.Show("一共还有" + dtCanPrize.Rows.Count + "人未中奖，请输入一个小于或等于" + dtCanPrize.Rows.Count + "的数字");
                return;
            }

            setPrizeArea(addCurrentPrizeCount);
            //dtCanPrizeIndex = 0;
            timer_scroll.Start();
            setStateBar("正在补抽"+ addCurrentPrizeCount + "位" + cbox_prize_list.Text );
            setBtnText(2);
        }

        private int startPrize()
        {
            
            //MessageBox.Show(currentPrize.ToString());
            //contextMenuStrip1.Items["addOne"].Enabled = false;
            

            DataTable dtPrize = helper.ExecuteDataTable("select * from bs_prize where ID=" + currentPrize, null);

            if (dtPrize.Rows.Count > 0)
            {
                //当前奖项剩余人数
                int prizeCount = int.Parse(dtPrize.Rows[0]["total"].ToString()) - int.Parse(dtPrize.Rows[0]["use_total"].ToString());
                if (prizeCount > 0) //抽奖正式开始
                {
                    if (prizeCount > dtCanPrize.Rows.Count) //剩余奖项 比 没中奖的人数多 提示是否继续
                    {
                        MessageBox.Show(cbox_prize_list.Text + "的剩余名额比参与抽奖的人数多");
                    }
                    if (prizeCount > allowPrizeCount) //剩余奖项 比 允许的单次抽奖人数多，则只能抽那么多，为了界面不混乱
                    {
                        prizeCount = allowPrizeCount;
                    }
                    setPrizeArea(prizeCount);
                    setStateBar("正在抽取" + cbox_prize_list.Text + "，已经抽取" + dtPrize.Rows[0]["use_total"].ToString() + "人 ,还有" + prizeCount + "个机会");
                    timer_scroll.Start();

                    allowMenuBtn(false);

                    return 0;
                }
                else
                {
                    MessageBox.Show(cbox_prize_list.Text + "已经抽完");
                    
                    return 1;
                }
                
            }
            else
            {
                MessageBox.Show("数据库中没有找到" + cbox_prize_list.Text);
                return 2; //没找到奖项
            }

            
        }

        /// <summary>
        /// 停止
        /// 如果允许重复中奖，则不删除dtCanPrize记录
        /// </summary>
        private void stopPrize()
        {
            timer_scroll.Stop();

            //contextMenuStrip1.Items["addOne"].Enabled = true;
            allowMenuBtn(true);

            dtWinner = new DataTable();

            dtWinner.Columns.Add("prize_id", typeof(int)); 
            dtWinner.Columns.Add("tel", typeof(string));

            //遍历出获奖者 ,添加到获奖者table（用于显示获奖名单）
            foreach (Control ctl in panel1.Controls)
            {
                if (ctl is Label && ctl.Name.StartsWith("prize_label_"))
                {
                    DataRow newRow;
                    newRow = dtWinner.NewRow();
                    newRow["prize_id"] = currentPrize; //当前奖项
                    newRow["tel"] = ctl.Text;
                    dtWinner.Rows.Add(newRow);

                    if (!ConfigHelper.get("repeat_flag").Equals("1")) //内存表中剔除中奖人
                    {
                        //dtCanPrize.Rows.Remove
                        for (int i = dtCanPrize.Rows.Count - 1; i >= 0; i--)
                        {
                            if (dtCanPrize.Rows[i]["tel"].ToString().Equals(ctl.Text))
                            {
                                dtCanPrize.Rows.RemoveAt(i);
                            }
                        }
                    }

                }
            }
            dtCanPrizeIndex = 0; //重置索引号

            if (dtWinner.Rows.Count > 0)
            {
                 //中奖人入库
                helper.UpdateAccess(dtWinner, "select prize_id,tel from bs_winner");

                DataTable dtTemp = helper.ExecuteDataTable("select * from bs_winner where valid_flag=1 and prize_id=" + currentPrize, null);

                helper.ExecuteNonQuery("update bs_prize set use_total="+dtTemp.Rows.Count+" where id="+currentPrize, null);

                setWinnerLabel(cbox_prize_list.Text, dtWinner);

            }
           
            
        }

        /// <summary>
        /// 设置滚动区数量
        /// </summary>
        /// <param name="count">数量</param>
        private void setPrizeArea(int count)
        {
            //清空当前
            for (int w = panel1.Controls.Count - 1; w >= 0; w--)
            {
                if (panel1.Controls[w] is Label && panel1.Controls[w].Name.StartsWith("prize_label_"))
                {
                    panel1.Controls.RemoveAt(w);
                    
                }
            }

            sumLabel = count;
            int rows = 1;
            int lineCount = 1;
            int indexNum = 1;
            int height = screenHeight /14;
            int width = screenWidth / 7;
            Point point = panel1.Location; // 起始坐标

            //处理奖品少的情况
            if (sumLabel <= 3) //一行显示三个
            {
                lineCount = sumLabel;
                //if (lineCount == 1)
                //{
                //    point = new Point(point.X + (panel1.Size.Width / 2) - 100, point.Y + (panel1.Size.Height / 2) - 35);
                //}
            }
            else
            {
                lineCount = 3;
                if (sumLabel % lineCount == 0)
                {
                    rows = (sumLabel / lineCount);
                }else{
                    rows = (sumLabel / lineCount) + 1;
                }
            }

            //开始画框框
            for (int i = 0; i < rows; i++) //行
            {
                for (int j = 0; j < lineCount; j++)
                {
                    Label label = new Label();
                    label.Name = "prize_label_" + indexNum;

                    if (screenWidth > 1400)
                    {
                        label.Font = new Font("隶书", 20, FontStyle.Bold);
                    }
                    else if(screenWidth > 1000 && screenWidth <=1400 )
                    {
                        label.Font = new Font("隶书", 17, FontStyle.Bold);
                    }
                    else
                    {
                        label.Font = new Font("隶书", 12, FontStyle.Bold);
                    }

                    if (sumLabel == 1)
                    {
                        label.Location = new Point(screenWidth / 2 - width*2, point.Y + height * i - (rows * height / 2) + height);
                    }
                    else
                    {
                        label.Location = new Point(point.X + width * j, point.Y + height * i - (rows * height / 2) + height);
                    }
                    
                    label.BackColor = Color.Transparent;
                    label.ForeColor = Color.Orange;
                    
                    label.AutoSize = true;

                    panel1.Controls.Add(label);
                    //panel1.Controls.SetChildIndex(label, 3);
                    indexNum++;
                    if (indexNum > sumLabel)
                    {
                        break;
                    }
                }
            }

        }

        /// <summary>
        /// 设置开始按钮的文字
        /// </summary>
        /// <param name="state"></param>
        private void setBtnText(int state)
        {
            if (state == null)
            {
                btnState++;
            }
            else
            {
                btnState = state;
            }
            
            if (btnState == 3)
            {
                btnState = 1;
            }
            switch (btnState){

                case 1 :
                    btn_begin.Text = "开  始";
                    reloadMusic("music_end.mp3");
                    break;
                case 2 :
                    btn_begin.Text = "停  止";
                    reloadMusic("music_begin.mp3");
                    
                    break;
                case 3:
                    btn_begin.Text = "下个奖项";
                    break;
                default:
                    break;

            }
        }

        #region 按钮经过修改样式
        private void btn_begin_MouseEnter(object sender, EventArgs e)
        {
            btn_begin.BackgroundImage = imageList1.Images[1];
            btn_begin.Update();
        }

        private void btn_begin_MouseLeave(object sender, EventArgs e)
        {
            btn_begin.BackgroundImage = imageList1.Images[0];
            btn_begin.Update();
        }
        #endregion

        

        private void timer_scroll_Tick(object sender, EventArgs e)
        {
            //int ret = 1; //执行成功返回1，否则返回0
            //dtCanPrizeIndex = 0;

            //System.Random r = new Random();
            //int i = r.Next(1, dtCanPrize.Rows.Count);
            //label_test.Text = i.ToString();

            int dtCanPrizeCount = dtCanPrize.Rows.Count; //能抽奖的人员总数

            foreach (Control ctl in panel1.Controls)
            {
                byte[] bytes = new byte[4];
                //使用加密服务提供程序 (CSP) 提供的实现来实现加密随机数生成器 (RNG)。
                System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
                //用经过加密的强随机值序列填充字节数组。
                rng.GetBytes(bytes);
                //将字节转换成32整数
                int n = BitConverter.ToInt32(bytes, 0);

                dtCanPrizeIndex = new Random(n).Next(0, dtCanPrizeCount); //

                if (ctl is Label && ctl.Name.StartsWith("prize_label_"))
                {
                    //if (dtCanPrizeIndex == dtCanPrizeCount)
                    //{
                    //    dtCanPrizeIndex = 0;
                    //}
                    ctl.Text = dtCanPrize.Rows[dtCanPrizeIndex]["tel"].ToString();
                    //dtCanPrizeIndex++;
                }
            }

        }

        /// <summary>
        /// 移除指定控件
        /// </summary>
        /// <param name="ctrl"></param>
        private void removeCtrls(Control ctrl)
        {
            panel1.Controls.Remove(ctrl);
        }

        private void cbox_prize_list_SelectedIndexChanged(object sender, EventArgs e)
        {
            int.TryParse(cbox_prize_list.SelectedValue.ToString(),out currentPrize);
            //MessageBox.Show(currentPrize.ToString());
        }

        private void about_Click(object sender, EventArgs e)
        {
            about form = new about();
            form.ShowDialog();
        }

        private void stopMusic_Click(object sender, EventArgs e)
        {
            player_bg.currentPlaylist.clear();//清除播放的内容
        }

        /// <summary>
        /// 设置奖区文字
        /// </summary>
        /// <param name="prize"></param>
        /// <param name="tel"></param>
        private void setWinnerLabel(string prize, DataTable dt)
        {
            if (dt.Rows.Count == 0)
            {
                return;
            }
            string str = "";
            str = label_winner.Text + "\r\n\r\n" + prize + "\r\n\r\n";
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                str = str + dt.Rows[i]["tel"].ToString() +"\r\n";
            }
            label_winner.Text = str;
        }


        private void resetWinnerLabel()
        {
            label_winner.Text = "";
        }

        private void timer_winner_Tick(object sender, EventArgs e)
        {
            //label_hjmd.Text;
            //panel_winner.Location;

            Point p;
            if ((label_winner.Location.Y + label_winner.Size.Height - 10) <= (label_hjmd.Location.Y + label_hjmd.Size.Height))
            {
                p = new Point(label_winner.Location.X, panel_winner.Location.Y + panel_winner.Size.Height);
            }
            else
            {
                p = new Point(label_winner.Location.X, label_winner.Location.Y - 1);
            }

            
            label_winner.Location = p;

        }

        private void allowMenuBtn(bool b){
            contextMenuStrip1.Items["addOne"].Enabled = b;
            contextMenuStrip1.Items["reset"].Enabled = b;
            contextMenuStrip1.Items["resetCurrent"].Enabled = b;
            cbox_prize_list.Enabled = b;
        }
        /// <summary>
        /// 中奖名单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void luckyList_Click(object sender, EventArgs e)
        {
            FormWinner form = new FormWinner();
            form.ShowDialog();
        }

        bool scollState = false;
        private void label_winner_MouseClick(object sender, MouseEventArgs e)
        {
            if (scollState)
            {
                timer_winner.Stop();
                scollState = false;
            }
            else
            {
                timer_winner.Start();
                scollState = true;
            }
        }
    }
}
